const fsPromises = require('fs').promises;
const path = require('path');
const compressing = require('compressing');

class FileSystem {
    constructor(url) {
        this.baseUrl = path.resolve(process.cwd(), url);
    }
    async removeDir(url = this.baseUrl) {
        const dirs = await fsPromises.readdir(url).catch(() => false);
        if (dirs) {
            for (const item of dirs) {
                const URL = path.join(url, item);
                const res = await fsPromises.stat(URL);
                res.isDirectory() && await this.removeDir(URL);
                res.isFile() && await fsPromises.unlink(URL);
            }
            fsPromises.rmdir(url);
        }
    }
    async createIconfontDir(data) {
        const arr = this.baseUrl.split(process.platform === 'win32' ? '\\' : '/');
        for (let i = 1, str = arr[ 0 ]; i < arr.length; i++) {
            str += `/${arr[ i ]}`;
            const bool = await fsPromises.readdir(str).catch(() => false);
            !bool && await fsPromises.mkdir(str);
        }
        return await this.uncompressZip(data);
    }
    async uncompressZip(data) {
        await compressing.zip.uncompress(data, this.baseUrl);
        const dirs = await fsPromises.readdir(this.baseUrl);
        for (const item of dirs) {
            const URL = path.join(this.baseUrl, item);
            const res = await fsPromises.stat(URL);
            if (res.isDirectory()) {
                const res = await fsPromises.readFile(path.join(URL, 'iconfont.css'), 'utf8');
                const regExp = new RegExp('\'iconfont', 'g');
                await fsPromises.writeFile(path.join(this.baseUrl, 'iconfont.css'), res.replace(regExp, `'./${item}/iconfont`));
                return path.join(item, 'iconfont.json');
            }
        }
    }
}
module.exports = FileSystem;
